﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GHRMS.APP.Classes;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using Telerik.Web.UI;
using KPIS.GERP.GHRMS.DAL;

namespace KPIS.GERP.GHRMS.APP.App_UI.UserControls
{
    public partial class PS_HisPrivateEdit : System.Web.UI.UserControl
    {
        private CommandControlBLL cmdFac = new CommandControlBLL();
        private IEmployeeBLL empBLL = new EmployeeBLL();
        private IAddressBLL addBLL = new AddressBLL();
        private IMasDistrictBLL districtBLL = new MasDistrictBLL();
        private IMasProvinceBLL provinceBLL = new MasProvinceBLL();
        private IMasBloodGroupBLL bgBLL = new MasBloodGroupBLL();
        private IMasNamePrefixBLL npBLL = new MasNamePrefixBLL();
        private IMasNationalitiesBLL natBLL = new MasNationalitiesBLL();
        private IMasReligionBLL relBLL = new MasReligionBLL();
        private IMasMaritalStatusBLL mrBLL = new MasMaritalStatusBLL();
        private IJobSiteBLL jsBLL = new JobSiteBLL();
        private IPositionBLL posBLL = new PositionBLL();
        private IExecutiveBLL exeBLL = new ExecutiveBLL();
        private IClassBLL classBLL = new ClassBLL();
        private IPositionTypeBLL ptBLL = new PositionTypeBLL();
        private IEmployeeTypeBLL etBLL = new EmployeeTypeBLL();
        private IEmployeeStatusBLL esBLL = new EmployeeStatusBLL();
        private EmpBookBankDAL bookBank = new EmpBookBankDAL();
        private FIM_MAS_Banks.FIM_MAS_Banks bank = new FIM_MAS_Banks.FIM_MAS_Banks();
        private SsMng ssMng = new SsMng();
        private Main main = new Main();
        private const int ItemsPerRequest = 10;
        ComboboxUtilites comboboxUtilites = new ComboboxUtilites(ItemsPerRequest);
        private const string fileDirectory = "../../OtherImages/Person";
        private const string fileImageNoImage = "~/App_UI/Images/Buttons/No Picture.jpg";

        protected void Page_Load(object sender, EventArgs e)
        {
            lbtEditPicture.Attributes.Add("onClick", "return false;");
            lbTPopup.Attributes.Add("onClick", "return false;");

            if (!IsPostBack)
            {
	            panelList2.Height = 500;
                //panelList2.Height = Unit.Pixel(500);
                //ViewState.Add("IsUserControlPostBack", true);
                BindEmployeeType();

                if (Session["EmpType"] != null)
                {
                    cmbEmployeeType.SelectedValue = Session["EmpType"].ToString();
                }

                BindNamePrefix();
                BindEmployeeStatus();
                //BindPositionType();
                BindNationalCombo();
                BindReligionCombo();
                BindBloodGroupCombo();
                BindMarStatusCombo();
                BindPosition();
                BindClass();
                BindExecPosition();
                BindJobSite();
                BindProvince();
                LoadBank();

                if (Request.QueryString["sta"] != null)
                {
                    lblSta.Text = Request.QueryString["sta"];
                }

                if (Request.QueryString["Sequence"].Length == 0)
                {
                    lblEmpSeq.Text = "";
                    ChangeMode(Main.EditMode.AddNew);
                }
                else
                {
                    lblEmpSeq.Text = Session["emp_seq"].ToString();
                    GetKeyValue(lblEmpSeq.Text);
                    ChangeMode(Main.EditMode.Info);
                }

                if (Request.QueryString["Editable"] != null && Request.QueryString["Editable"] == "0")
                {
                    Edit.Visible = false;
                }
            }
        }

#region Load Data 

        public void GetKeyValue(string Sequence)
        {
            DataRow employeeData = GetEmployee(Sequence);

            if (employeeData != null)
            {
	            var posTypeData = posBLL.GetJobSiteAndPositionTypeAndClassByPosition(employeeData["POS_SEQ"].ToString());
                lblOfficialID.Text = employeeData["OFFICIAL"].ToString();
                txtOfficialID.Text = lblOfficialID.Text;

                lblEmployeeType.Text = employeeData["EMP_TYPE_NAME"].ToString();
                cmbEmployeeType.SelectedValue = employeeData["EMP_TYPE_SEQ"].ToString();

                lblNamePrefix.Text = employeeData["PREFIX_NAME"].ToString();
                lblNamePrefixEng.Text = employeeData["PREFIX_NAME_ENG"].ToString();
                cmbNamePrefix.SelectedValue = employeeData["NAME_PREFIX_SEQ"].ToString();

                lblPosition.Text = employeeData["POS_REF"].ToString() + "  " + employeeData["POS_NAME"].ToString();
                cmbPosition.SelectedValue = employeeData["POS_SEQ"].ToString();

                lblExecPosition.Text = employeeData["EXEC_POS_NAME"].ToString();
                cmbExecPosition.SelectedValue = employeeData["EXEC_POS_SEQ"].ToString();

                lblBloodGroup.Text = employeeData["BLOOD_GROUP_NAME"].ToString();
                cmbBloodGroup.SelectedValue = employeeData["BLOOD_GROUP_SEQ"].ToString();
                lblRaceNational.Text = employeeData["RACE_NAT_NAME"].ToString();
                cmbRaceNational.SelectedValue = employeeData["RACE_NAT_SEQ"].ToString();
                lblNational.Text = employeeData["NAT_NAME"].ToString();
                cmbNational.SelectedValue = employeeData["NAT_SEQ"].ToString();
                lblReligion.Text = employeeData["RELIGION_NAME"].ToString();
                cmbReligion.SelectedValue = employeeData["RELIGION_SEQ"].ToString();
                lblMarStatus.Text = employeeData["MAR_STAT_NAME"].ToString();
                cmbMarStatus.SelectedValue = employeeData["MAR_STAT_SEQ"].ToString();

                lblPositionType.Text = posTypeData["pos_type_name"].ToString();
                SetLabelText_LabelPositionTypeEditMode(posTypeData["pos_type_name"]);
				//cmbPositionType.SelectedValue = employeeData["POS_TYPE_SEQ"].ToString();
				hdfPositionType.Value = employeeData["POS_TYPE_SEQ"].ToString();
                BindClass();

                lblClass.Text = employeeData["CLASS_NAME"].ToString();
                cmbClass.SelectedValue = employeeData["CLASS_SEQ"].ToString();
				if(string.IsNullOrEmpty(employeeData["CLASS_SEQ"].ToString()))
				{
					//cmbClass.SelectedValue = posTypeData["class_seq"];
				}
				
                lblJobSite.Text = employeeData["JOB_SITE_NAME"].ToString();
	            SetLabelText_LabelJobSiteEditMode(employeeData["JOB_SITE_NAME"].ToString());
                //cmbJobSite.SelectedValue = employeeData["JOB_SITE_SEQ"].ToString();

                lblWorkingJobSite.Text = employeeData["WORKING_JOB_SITE_NAME"].ToString();
                cmbWorkingJobSite.SelectedValue = employeeData["WORKING_JOB_SITE_SEQ"].ToString();

                lblStatus.Text = employeeData["EMP_STATUS_NAME"].ToString();
                cmbStatus.SelectedValue = employeeData["EMP_STATUS_SEQ"].ToString();

                lblFirstName.Text = employeeData["FIRST_NAME"].ToString();
                txtFirstName.Text = employeeData["FIRST_NAME"].ToString();
                lblLastName.Text = employeeData["LAST_NAME"].ToString();
                txtLastName.Text = employeeData["LAST_NAME"].ToString();
                lblFirstNameEng.Text = employeeData["FIRST_NAME_ENG"].ToString();
                txtFirstNameEng.Text = employeeData["FIRST_NAME_ENG"].ToString();
                lblLastNameEng.Text = employeeData["LAST_NAME_ENG"].ToString();
                txtLastNameEng.Text = employeeData["LAST_NAME_ENG"].ToString();
                lblCitizen.Text = employeeData["CITIZEN"].ToString();
                txtCitizenMasked.Text = employeeData["CITIZEN"].ToString();
                
                txtBirthDate.SetValue(employeeData["BIRTH_DATE"]);
                lblBirthDate.Text = txtBirthDate.GetStringValue();
                
                txtDateAdmitted.SetValue(employeeData["DATE_ADMITTED"]);
                lblDateAdmitted.Text = txtDateAdmitted.GetStringValue();
                lblAdmittedCount.Text = employeeData["ADMITTED_COUNT"].ToString();
                
                txtWorkingDate.SetValue(employeeData["DATE_WORK_START"]);
                lblWorkingDate.Text = txtWorkingDate.GetStringValue();
                DateTime dtmRetireDate = DateTime.Now;
                lblRetireDate.Text = (DateTime.TryParse(employeeData["RETIRE_DATE"].ToString(), out dtmRetireDate)
                    ? dtmRetireDate.ToShortDateString() : "");
                
                txtDatePosition.SetValue(employeeData["DATE_LATEST_POS"]);
                lblDatePosition.Text = txtDatePosition.GetStringValue();
                lblPositionCount.Text = employeeData["POSITION_COUNT"].ToString();

                double dblSalary = 0;
                if (double.TryParse(employeeData["SALARY"].ToString(), out dblSalary))
                {
                    lblSalary.Text = dblSalary.ToString("#,##0");
                    txtSalary.Text = dblSalary.ToString();
                }
                else
                {
                    lblSalary.Text = "0";
                    txtSalary.Text = "0";
                }

                lblBookSeq.Text = employeeData["book_seq"].ToString();
                lblBankAccNo.Text = employeeData["bank_acc_no"].ToString();
                lblBankName.Text = employeeData["bank_name"].ToString();
                lblBranchName.Text = employeeData["branch_name"].ToString();
                txtBankAccNo.Text = employeeData["bank_acc_no"].ToString();
                ddlBank.SelectedValue = employeeData["bank_seq"].ToString();
                ddlBank_SelectedIndexChanged(null, null);
                ddlBranch.SelectedValue = employeeData["branch_seq"].ToString();

                ///lblCodeScan.Text = employeeData["CODE_SCAN"].ToString();
                ///txtCodeScan.Text = employeeData["CODE_SCAN"].ToString();
                hdImg.Value = employeeData["image_unique"].ToString();

                LoadAddress();

                if (!String.IsNullOrEmpty(hdImg.Value) &&
                    File.Exists(GetImageFullPath(hdImg.Value)))
                {
                    imgPhoto.ImageUrl = GetImageUrl(hdImg.Value);
                }
                else
                {
                    imgPhoto.ImageUrl = fileImageNoImage;
                }
            }
        }

        protected void LoadAddress()
        {
            DataSet ds = addBLL.LoadEmployeeAddress(Convert.ToInt32(lblEmpSeq.Text), null);
            Dictionary<string, string> adrCont = GetAddress(ds, 1);
            Dictionary<string, string> adrHome = GetAddress(ds, 2);

            if (adrCont != null)
            {
                lblTelContact.Text = adrCont["TEL"];
                txtTelContact.Text = adrCont["TEL"];
                lblEmail.Text = adrCont["EMAIL"];
                txtEmail.Text = adrCont["EMAIL"];
                lblAddress1.Text = adrCont["ADDRESS_SEQ"];
                lblAddressContact.Text = adrCont["ADDRESS_DESCR"];
                txtAddressContact.Text = adrCont["ADDRESS_DESCR"];
                lblDistrictContact.Text = adrCont["DIS_AMP_PROV"];
                cmbProvinceContact.SelectedValue = adrCont["PROVINCE_SEQ"];
                BindDistrictContact();
                cmbDistrictContact.SelectedValue = adrCont["DISTRICT_SEQ"];
            }
            else
            {
                lblAddress1.Text = String.Empty;
                txtAddressContact.Text = String.Empty;
                cmbProvinceContact.SelectedIndex = 0;
                BindDistrictContact();
                cmbDistrictContact.SelectedIndex = 0;
            }

            if (adrHome != null)
            {
                lblAddress2.Text = adrHome["ADDRESS_SEQ"];
                lblAddressHome.Text = adrHome["ADDRESS_DESCR"];
                txtAddressHome.Text = adrHome["ADDRESS_DESCR"];
                lblDistrictHome.Text = adrHome["DIS_AMP_PROV"];
                cmbProvinceHome.SelectedValue = adrHome["PROVINCE_SEQ"];
                BindDistrictHome();
                cmbDistrictHome.SelectedValue = adrHome["DISTRICT_SEQ"];
            }
            else
            {
                lblAddress2.Text = String.Empty;
                txtAddressHome.Text = String.Empty;
                cmbProvinceHome.SelectedIndex = 0;
                BindDistrictHome();
                cmbDistrictHome.SelectedIndex = 0;
            }
        }

#endregion Load Data

#region BindDataCombobox

        private void BindNamePrefix()
        {
            cmbNamePrefix.DataSource = npBLL.ListNamePrefixes();
            cmbNamePrefix.DataBind();

            cmbNamePrefix.Items.Insert(0, new RadComboBoxItem("--เลือกคำนำหน้าชื่อ--", ""));
        }

        private void BindEmployeeType()
        {
            try
            {
                IList<EmployeeTypeInfo> infoList = etBLL.ListEmployeeTypes();
                cmbEmployeeType.DataSource = infoList;
                cmbEmployeeType.DataBind();
            }
            catch (Exception error)
            {
                throw error;
            }
        }

        private void BindEmployeeStatus()
        {
            try
            {
                IList<EmployeeStatusInfo> infoList = esBLL.LoadListEmployeeStatus();
                cmbStatus.DataSource = infoList;
                cmbStatus.DataBind();
            }
            catch (Exception error)
            {
                throw error;
            }
        }

		//private void BindPositionType()
		//{
		//	int? EmployeeType = String.IsNullOrEmpty(cmbEmployeeType.SelectedValue) ? (int?) null : Int32.Parse(cmbEmployeeType.SelectedValue);
		//	try
		//	{
		//		IList<PositionTypeInfo> infoList = ptBLL.ListPositionTypes(null, EmployeeType);
		//		cmbPositionType.DataSource = infoList;
		//		cmbPositionType.DataBind();

		//		cmbPositionType.Items.Insert(0, new RadComboBoxItem("--เลือกประเภทตำแหน่ง--", ""));
		//	}
		//	catch (Exception error)
		//	{
		//		throw error;
		//	}
		//}

        private void BindExecPosition()
        {
            IList<ExecutiveInfo> infoList = exeBLL.ListExecutives(null, "U");
            infoList.Insert(0, new ExecutiveInfo{Sequence = null, Name = "--เลือกตำแหน่งการบริหาร (ถ้ามี)--"});
            cmbExecPosition.DataSource = infoList;
            cmbExecPosition.DataBind();
        }

        private void BindNationalCombo()
        {
            IList<MasNationalitiesInfo> infoList = natBLL.ListNationalities();

            cmbRaceNational.DataSource = infoList;
            cmbRaceNational.DataBind();

            cmbNational.DataSource = infoList;
            cmbNational.DataBind();
        }

        protected void BindReligionCombo()
        {
            IList<MasReligionInfo> infoList = relBLL.ListReligions();

            cmbReligion.DataSource = infoList;
            cmbReligion.DataBind();
        }

        protected void BindBloodGroupCombo()
        {
            IList<MasBloodGroupInfo> infoList = bgBLL.ListBloodGroups("");

            cmbBloodGroup.DataSource = infoList;
            cmbBloodGroup.DataBind();
        }

        protected void BindMarStatusCombo()
        {
            IList<MasMaritalStatusInfo> infoList = mrBLL.ListMaritalStatus(null);

            cmbMarStatus.DataSource = infoList;
            cmbMarStatus.DataBind();
        }

        protected void BindPosition()
        {
            cmbPosition.DataSource = posBLL.LoadPositions(null, main.ConvertNullInt(cmbEmployeeType.SelectedValue), null, "").Tables[0];
            cmbPosition.DataBind();

            cmbPosition.Items.Insert(0, new RadComboBoxItem("--เลือกตำแหน่ง--", ""));
        }

        protected void BindJobSite()
        {
            //cmbJobSite.DataSource = jsBLL.LoadJobSiteSearchText(SystemInfo._JobsiteExternal, "", ""); //posBLL.LoadPositions(null, main.ConvertNullInt(cmbEmployeeType.SelectedValue), null, "").Tables[0];
            //cmbJobSite.DataBind();

            cmbWorkingJobSite.DataSource = jsBLL.LoadJobSiteSearchText(SystemInfo._JobsiteInternal, "", "");
            cmbWorkingJobSite.DataBind();

            //cmbJobSite.Items.Insert(0, new RadComboBoxItem("--เลือกหน่วยงาน--", ""));
            cmbWorkingJobSite.Items.Insert(0, new RadComboBoxItem("--เลือกหน่วยงาน--", ""));
        }

        protected void BindClass()
        {
			//int? posTypeSequence = string.IsNullOrEmpty(hdfPositionType.Value)//cmbPositionType.SelectedValue)
			//											? (int?)null
			//											: Int32.Parse(hdfPositionType.Value);//cmbPositionType.SelectedValue);

	        var result = posBLL.GetJobSiteAndPositionTypeAndClassByPosition(cmbPosition.SelectedValue);

            //int? posTypeSequence = null;    // string.IsNullOrWhiteSpace(result["pos_type_seq"]) ? (int?)null : Convert.ToInt32(result["pos_type_seq"]);
            int? posTypeSequence = string.IsNullOrEmpty(result["pos_type_seq"]) ? (int?)null : Convert.ToInt32(result["pos_type_seq"]);


            cmbClass.Items.Clear();
            if (posTypeSequence == null)
            {
                cmbClass.Items.Insert(0, new RadComboBoxItem("--เลือกประเภทตำแหน่งก่อน--", ""));
            }
            else
            {
                //cmbClass.DataSource = classBLL.LoadClasses((int?)null, posTypeSequence, (int?)null);
                cmbClass.DataSource = classBLL.LoadClasses((int?)null, posTypeSequence, Convert.ToInt32(Session["EmpType"]));
                cmbClass.DataBind();

                cmbClass.Items.Insert(0, new RadComboBoxItem("--เลือกระดับตำแหน่ง--", ""));

	            cmbClass.SelectedValue = result["class_seq"];
            }
        }

        private void BindProvince()
        {
            DataTable dtb = provinceBLL.LoadMasProvinces(null, null).Tables[0];
            cmbProvinceHome.DataSource = dtb;
            cmbProvinceContact.DataSource = dtb;
            cmbDistrictContact.DataBind();
            cmbProvinceHome.DataBind();
            cmbProvinceContact.DataBind();

            cmbProvinceHome.Items.Insert(0, new RadComboBoxItem("--เลือกจังหวัด--", ""));
            cmbDistrictHome.Items.Insert(0, new RadComboBoxItem("--กรุณาเลือกจังหวัดก่อน--", ""));
            cmbProvinceContact.Items.Insert(0, new RadComboBoxItem("--เลือกจังหวัด--", ""));
            cmbDistrictContact.Items.Insert(0, new RadComboBoxItem("--กรุณาเลือกจังหวัดก่อน--", ""));
        }

        private void BindDistrictHome()
        {
            if (cmbProvinceHome.SelectedValue.Length > 0)
            {
                DataTable dtb = districtBLL.LoadDistricts(null, null, main.ConvertNullInt(cmbProvinceHome.SelectedValue), "").Tables[0];
                cmbDistrictHome.DataSource = dtb;
                cmbDistrictHome.DataBind();

                cmbDistrictHome.Items.Insert(0, new RadComboBoxItem("--เลือกตำบล/อำเภอ--", ""));
                cmbDistrictHome.Focus();
            }
        }

        private void BindDistrictContact()
        {
            if (cmbProvinceContact.SelectedValue.Length > 0)
            {
                DataTable dtb = districtBLL.LoadDistricts(null, null, main.ConvertNullInt(cmbProvinceContact.SelectedValue), "").Tables[0];
                cmbDistrictContact.DataSource = dtb;
                cmbDistrictContact.DataBind();

                cmbDistrictContact.Items.Insert(0, new RadComboBoxItem("--เลือกตำบล/อำเภอ--", ""));
                cmbDistrictContact.Focus();
            }
		}

		private void BindJobSiteAndPositionTypeFromPositionSelected()
		{
			var data = posBLL.GetJobSiteAndPositionTypeAndClassByPosition(cmbPosition.SelectedValue);
			SetLabelText_LabelJobSiteEditMode(data["job_site_name"]);
			SetLabelText_LabelPositionTypeEditMode(data["pos_type_name"]);
		}

#endregion BindDataCombobox
        
#region Validate Data

        protected bool CheckData()
        {
            List<string> strError = new List<string>();
            if (cmbEmployeeType.SelectedValue.Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("ประเภทบุคลากร"));
            }
            if (cmbNamePrefix.SelectedValue.Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("คำนำหน้าชื่อ"));
            }
            if (txtFirstName.Text.Trim().Length == 0 || txtLastName.Text.Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("ชื่อ - นามสกุล"));
            }
            if (txtCitizenMasked.Text.Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("เลขบัตรประจำตัวประชาชน"));
            }
            if (txtCitizenMasked.Text.Trim().Length < 13)
            {
                strError.Add(main.ErrorEmpty("เลขบัตรประจำตัวประชาชน มีจำนวนน้อยกว่า 13 ตัว"));
            }
            if (txtBirthDate.GetStringValue().Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("วัน เดือน ปีเกิด"));
            }
            if (cmbMarStatus.SelectedValue.Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("สถานะภาพ(สมรส)"));
            }
            if (cmbPosition.SelectedValue.Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("ดำรงตำแหน่ง"));
            }
			//if (cmbPositionType.SelectedValue.Trim().Length == 0)
			//{
			//	strError.Add(main.ErrorEmpty("ประเภทตำแหน่ง"));
			//}
			//if (cmbClass.SelectedValue.Trim().Length == 0)
			//{
			//	strError.Add(main.ErrorEmpty("ระดับตำแหน่ง"));
			//}
			//if (cmbJobSite.SelectedValue.Trim().Length == 0)
			//{
			//	strError.Add(main.ErrorEmpty("สังกัดตามโครงสร้างกฏกระทรวง"));
			//}
            if (cmbWorkingJobSite.SelectedValue.Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("สังกัดตามโครงสร้างการบริหารจัดการ"));
            }
            if (txtSalary.Text.Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("เงินเดือน"));
            }
            if (cmbStatus.SelectedValue.Trim().Length == 0)
            {
                strError.Add(main.ErrorEmpty("สถานะการปฏิบัติราชการ"));
            }
            EmployeeInfo employeeOfSelectedPosition = posBLL.LoadEmployeeOfPosition(cmbPosition.SelectedValue);
            if (employeeOfSelectedPosition != null && 
                    (
                        String.IsNullOrEmpty(lblEmpSeq.Text) ||
                        !String.IsNullOrEmpty(lblEmpSeq.Text) && employeeOfSelectedPosition.Sequence != Int32.Parse(lblEmpSeq.Text)
                    )
                )
            {
                    strError.Add("มีบุคคลดำรงตำแหน่งนี้อยู่แล้ว");
            }   

            if (strError.Count > 0)
            {
                main.MessageAlert(Page, String.Join(@"\n", strError.ToArray()));
                return false;
            }
            return true;
        }

#endregion Validate Data

#region General Event

        protected void Edit_Click(object sender, EventArgs e)
        {
            ChangeMode(Main.EditMode.Edit);
        }

        private void ChangeMode(Main.EditMode mode)
        {
            switch (mode)
            {
                case Main.EditMode.AddNew:
                    Edit.Visible = false;
                    Save_Edit.Visible = false;
                    Save_AddNew.Visible = true;
                    Cancel.Visible = false;

                    lblMode.Text = "เพิ่มรายการใหม่";
		            lblPositionTypeEditMode.Visible = true;
		            lblJobSiteEditMode.Visible = true;
                    SetControlEditable(true);
                    break;
                case Main.EditMode.Edit:
                    Edit.Visible = false;
                    Save_Edit.Visible = true;
                    Save_AddNew.Visible = false;
                    Cancel.Visible = true;

                    lblMode.Text = "แก้ไขข้อมูล";
		            lblPositionTypeEditMode.Visible = true;
		            lblJobSiteEditMode.Visible = true;
                    SetControlEditable(true);
                    break;
                case Main.EditMode.Info:
                    Edit.Visible = true;
                    Save_Edit.Visible = false;
                    Save_AddNew.Visible = false;
                    Cancel.Visible = false;

                    lblMode.Text = "ข้อมูลบุคลากร";
		            lblPositionTypeEditMode.Visible = false;
		            lblJobSiteEditMode.Visible = false;
                    SetControlEditable(false);
                    break;
                case Main.EditMode.View:
                    break;
                default:
                    break;
            }
        }

        private void SetControlEditable(bool bEdit)
        {
            lblEmployeeType.Visible = !bEdit;
            cmbEmployeeType.Visible = bEdit;

            lblOfficialID.Visible = !bEdit;
            txtOfficialID.Visible = bEdit;

            lblNamePrefix.Visible = !bEdit;
            cmbNamePrefix.Visible = bEdit;

            lblFirstName.Visible = !bEdit;
            txtFirstName.Visible = bEdit;
            lblLastName.Visible = !bEdit;
            txtLastName.Visible = bEdit;

            pnlPrefixEng.Visible = !bEdit;

            lblFirstNameEng.Visible = !bEdit;
            txtFirstNameEng.Visible = bEdit;
            lblLastNameEng.Visible = !bEdit;
            txtLastNameEng.Visible = bEdit;

            lblCitizen.Visible = !bEdit;
            txtCitizenMasked.Visible = bEdit;

            lblBirthDate.Visible = !bEdit;
            txtBirthDate.Visible = bEdit;

            lblDateAdmitted.Visible = !bEdit;
            txtDateAdmitted.Visible = bEdit;
            lblCaptionAdmittedCount.Visible = !bEdit;
            lblAdmittedCount.Visible = !bEdit;

            lblWorkingDate.Visible = !bEdit;
            txtWorkingDate.Visible = bEdit;
            lblCaptionRetryDate.Visible = !bEdit;
            lblRetireDate.Visible = !bEdit;

            lblPosition.Visible = !bEdit;
            cmbPosition.Visible = bEdit;

            lblDatePosition.Visible = !bEdit;
            txtDatePosition.Visible = bEdit;
            lblCaptionPositionCount.Visible = !bEdit;
            lblPositionCount.Visible = !bEdit;

            lblPositionType.Visible = !bEdit;
            //cmbPositionType.Visible = bEdit;

            lblExecPosition.Visible = !bEdit;
            cmbExecPosition.Visible = bEdit;

            lblClass.Visible = !bEdit;
            cmbClass.Visible = bEdit;

            lblJobSite.Visible = !bEdit;
            //cmbJobSite.Visible = bEdit;

            lblWorkingJobSite.Visible = !bEdit;
            cmbWorkingJobSite.Visible = bEdit;

            lblSalary.Visible = !bEdit;
            txtSalary.Visible = bEdit;

            lblBankAccNo.Visible = !bEdit;
            txtBankAccNo.Visible = bEdit;

            lblBankName.Visible = !bEdit;
            ddlBank.Visible = bEdit;

            lblBranchName.Visible = !bEdit;
            ddlBranch.Visible = bEdit;

            lblStatus.Visible = !bEdit;
            cmbStatus.Visible = bEdit;

            lblCodeScan.Visible = !bEdit;
            txtCodeScan.Visible = bEdit;

            lblBloodGroup.Visible = !bEdit;
            cmbBloodGroup.Visible = bEdit;

            lblMarStatus.Visible = !bEdit;
            cmbMarStatus.Visible = bEdit;

            lblRaceNational.Visible = !bEdit;
            cmbRaceNational.Visible = bEdit;

            lblNational.Visible = !bEdit;
            cmbNational.Visible = bEdit;

            lblReligion.Visible = !bEdit;
            cmbReligion.Visible = bEdit;

            lblAddressHome.Visible = !bEdit;
            txtAddressHome.Visible = bEdit;

            lblDistrictHome.Visible = !bEdit;
            cmbDistrictHome.Visible = bEdit;
            cmbProvinceHome.Visible = bEdit;

            lblAddressContact.Visible = !bEdit;
            txtAddressContact.Visible = bEdit;

            lblDistrictContact.Visible = !bEdit;
            cmbDistrictContact.Visible = bEdit;
            cmbProvinceContact.Visible = bEdit;

            lblTelContact.Visible = !bEdit;
            txtTelContact.Visible = bEdit;

            lblEmail.Visible = !bEdit;
            txtEmail.Visible = bEdit;

            lbtEditPicture.Visible = bEdit;
        }

        protected void AddNewSave_Click(object sender, EventArgs e)
        {
            if (!CheckData())
            {
                return;
            }

            try
            {
                int? posisionType = null;
                int tempPositionType;
                if(Int32.TryParse(/*cmbPositionType.SelectedValue*/ hdfPositionType.Value, out tempPositionType))
                {
                    posisionType = tempPositionType;
                }

                string GenderSeq = empBLL.GetGenderSeq(cmbNamePrefix.SelectedValue).ToString();
                
                lblEmpSeq.Text = empBLL.Insert(txtFirstName.Text.Trim()
                                               , txtLastName.Text.Trim()
                                               , txtFirstNameEng.Text.Trim()
                                               , txtLastNameEng.Text.Trim()
                                               , null // NickName
                                               , txtCitizenMasked.Text.Trim()
                                               , null // Tax Payer
                                               , "" // Social
                                               , txtOfficialID.Text.Trim()
                                               , cmbNamePrefix.SelectedValue
                                               , GenderSeq // Gender
                                               , cmbReligion.SelectedValue
                                               , cmbRaceNational.SelectedValue
                                               , cmbNational.SelectedValue
                                               , cmbBloodGroup.SelectedValue
                                               ,
                                               txtBirthDate.GetStringValue().Length > 0
                                                   ? DateTime.Parse(txtBirthDate.GetStringValue())
                                                   : (DateTime?) null
                                               , null // DeathDate
                                               , cmbEmployeeType.SelectedValue
                                               , cmbClass.SelectedValue
                                               , null // SalaryLevel
                                               ,
                                               string.IsNullOrEmpty(txtSalary.Text)
                                                   ? (double?) null
                                                   : double.Parse(txtSalary.Text) // Salary
                                               , cmbPosition.SelectedValue
                                               , cmbWorkingJobSite.SelectedValue
                                               ,
                                               txtDateAdmitted.GetStringValue().Length > 0
                                                   ? DateTime.Parse(txtDateAdmitted.GetStringValue())
                                                   : (DateTime?) null
                                               ,
                                               txtWorkingDate.GetStringValue().Length > 0
                                                   ? DateTime.Parse(txtWorkingDate.GetStringValue())
                                                   : (DateTime?) null // WorkStartDate
                                               , null // DateQuit
                                               , cmbStatus.SelectedValue //Status
                                               , true // FundMember
                                               //, cmbMarStatus.SelectedValue
                                               , null //
                                               ,
                                               txtDatePosition.GetStringValue().Length > 0
                                                   ? DateTime.Parse(txtDatePosition.GetStringValue())
                                                   : (DateTime?) null
                                               , null // DateLatedClass
                                               , null // DateWorkingJobSite
                                               // , txtCodeScan.Text.Trim()
                                               , ssMng.EmpSeqI
                                               , cmbMarStatus.SelectedValue
                                               , txtCodeScan.Text
                                               , posisionType
                                               , hdImg.Value
                                               , cmbExecPosition.SelectedValue
                    );

                Session["emp_seq"] = lblEmpSeq.Text;

                if (string.IsNullOrEmpty(lblAddress1.Text))
                {
                    addBLL.InsertAddressContact(Int32.Parse(lblEmpSeq.Text)
                                                , txtAddressContact.Text.Trim()
                                                , cmbDistrictContact.SelectedValue
                                                , ""
                                                , "140"
                                                , ""
                                                , txtTelContact.Text.Trim()
                                                , ""
                                                , txtEmail.Text.Trim()
                                                , ssMng.EmpSeqI);
                }
                else
                {
                    addBLL.UpdateAddressContact(Int32.Parse(lblAddress1.Text)
                                                , txtAddressContact.Text.Trim()
                                                , cmbDistrictContact.SelectedValue
                                                , ""
                                                , "140"
                                                , ""
                                                , txtTelContact.Text.Trim()
                                                , ""
                                                , txtEmail.Text.Trim()
                                                , ssMng.EmpSeqI);
                }

                if (string.IsNullOrEmpty(lblAddress2.Text))
                {
                    addBLL.InsertAddressHome(Int32.Parse(lblEmpSeq.Text)
                                             , txtAddressHome.Text.Trim()
                                             , cmbDistrictHome.SelectedValue
                                             , ""
                                             , "140"
                                             , ""
                                             , "" //txtTelh.Text.Trim()
                                             , ssMng.EmpSeqI);
                }
                else
                {
                    addBLL.UpdateAddressHome(Int32.Parse(lblAddress2.Text)
                                             , txtAddressHome.Text.Trim()
                                             , cmbDistrictHome.SelectedValue
                                             , ""
                                             , "140"
                                             , ""
                                             , "" //txtTelContact.Text.Trim()
                                             , ssMng.EmpSeqI);
                }

                //if (string.IsNullOrEmpty(txtBankAccNo.Text) && string.IsNullOrEmpty(ddlBank.SelectedValue) && string.IsNullOrEmpty(ddlBranch.SelectedValue))
                //{
                bookBank.Insert(lblEmpSeq.Text, null, txtBankAccNo.Text, ddlBank.SelectedValue,ddlBranch.SelectedValue
                    , null, "U", ssMng.EmpSeq);
                //}

                GetKeyValue(lblEmpSeq.Text);
                ChangeMode(Main.EditMode.Info);
                //cmdFac.CancelCommand(panelList2, panelGrid, panelCommand);
                //lblMode.Text = "ข้อมูลบุคลากร";
                //DatePickerCommand(false);
                //lbtEditPicture.Visible = false;
                //// main.ReloadCurrentPage(Page, "บันทึกข้อมูลนี้แล้ว จะทำการรีโหลดหน้าเว็ป");
                //HttpContext.Current.Response.Redirect(Request.Url.OriginalString + lblEmpSeq.Text, false);

				main.MessageAlert(Page, "บันทึกข้อมูลแล้ว");
            }
            catch (Exception error)
            {
                main.MessageAlert(Page, error.Message);
            }

        }

        protected void EditSave_Click(object sender, EventArgs e)
        {
            if (!CheckData())
            {
                return;
            }
            string GenderSeq = empBLL.GetGenderSeq(cmbNamePrefix.SelectedValue).ToString();
            try
            {
                empBLL.Update(Int32.Parse(lblEmpSeq.Text)
                              , txtFirstName.Text.Trim()
                              , txtLastName.Text.Trim()
                              , txtFirstNameEng.Text.Trim()
                              , txtLastNameEng.Text.Trim()
                              , "" // NickName
                              , txtCitizenMasked.Text.Trim()
                              , "" // Tax Payer
                              , "" // Social
                              , txtOfficialID.Text.Trim()
                              , cmbNamePrefix.SelectedValue
                              , GenderSeq // Gender
                              , cmbReligion.SelectedValue
                              , cmbRaceNational.SelectedValue
                              , cmbNational.SelectedValue
                              , cmbBloodGroup.SelectedValue
                              ,
                              txtBirthDate.GetStringValue().Length > 0
                                  ? DateTime.Parse(txtBirthDate.GetStringValue())
                                  : (DateTime?) null
                              , (DateTime?) null // DeathDate
                              , cmbEmployeeType.SelectedValue
                              , cmbClass.SelectedValue
                              , (int?) null // SalaryLevel
                              , string.IsNullOrEmpty(txtSalary.Text) ? (double?) null : double.Parse(txtSalary.Text)
                              // Salary
                              , cmbPosition.SelectedValue
                              , cmbWorkingJobSite.SelectedValue
                              ,
                              txtDateAdmitted.GetStringValue().Length > 0
                                  ? DateTime.Parse(txtDateAdmitted.GetStringValue())
                                  : (DateTime?) null
                              ,
                              txtWorkingDate.GetStringValue().Length > 0
                                  ? DateTime.Parse(txtWorkingDate.GetStringValue())
                                  : (DateTime?) null // WorkStartDate
                              , (DateTime?) null // DateQuit
                              , cmbStatus.SelectedValue //Status
                              , true // FundMember
                              , cmbMarStatus.SelectedValue
                              , (DateTime?) null //
                              ,
                              txtDatePosition.GetStringValue().Length > 0
                                  ? DateTime.Parse(txtDatePosition.GetStringValue())
                                  : (DateTime?) null
                              , (DateTime?) null // DateLatedClass
                              , (DateTime?) null // DateWorkingJobSite
                              , txtCodeScan.Text.Trim()
                              , ssMng.EmpSeqI
                              , !string.IsNullOrEmpty(hdfPositionType.Value) ? (int?) Convert.ToInt32(hdfPositionType.Value) : null  // cmbPositionType.SelectedValue.Length > 0 ? Convert.ToInt32(cmbPositionType.SelectedValue) : (int?) null
                              , hdImg.Value
                              , cmbExecPosition.SelectedValue);

                if (String.IsNullOrEmpty(lblAddress1.Text))
                {
                    addBLL.InsertAddressContact(Int32.Parse(lblEmpSeq.Text)
                                                , txtAddressContact.Text.Trim()
                                                , cmbDistrictContact.SelectedValue
                                                , ""
                                                , "140"
                                                , ""
                                                , txtTelContact.Text.Trim()
                                                , ""
                                                , txtEmail.Text.Trim()
                                                , ssMng.EmpSeqI);
                }
                else
                {
                    addBLL.UpdateAddressContact(Int32.Parse(lblAddress1.Text)
                                                , txtAddressContact.Text.Trim()
                                                , cmbDistrictContact.SelectedValue
                                                , ""
                                                , "140"
                                                , ""
                                                , txtTelContact.Text.Trim()
                                                , ""
                                                , txtEmail.Text.Trim()
                                                , ssMng.EmpSeqI);
                }

                if (String.IsNullOrEmpty(lblAddress2.Text))
                {
                    addBLL.InsertAddressHome(Int32.Parse(lblEmpSeq.Text)
                                             , txtAddressHome.Text.Trim()
                                             , cmbDistrictHome.SelectedValue
                                             , ""
                                             , "140"
                                             , ""
                                             , "" //txtTelh.Text.Trim()
                                             , ssMng.EmpSeqI);
                }
                else
                {
                    addBLL.UpdateAddressHome(Int32.Parse(lblAddress2.Text)
                                             , txtAddressHome.Text.Trim()
                                             , cmbDistrictHome.SelectedValue
                                             , ""
                                             , "140"
                                             , ""
                                             , "" //txtTelContact.Text.Trim()
                                             , ssMng.EmpSeqI);
                }

                //DataTable dtb = bookBank.ListData();
                if (lblBookSeq.Text.Length > 0)
                {
                    bookBank.Update(lblBookSeq.Text, lblEmpSeq.Text, null, txtBankAccNo.Text, ddlBank.SelectedValue, ddlBranch.SelectedValue
                        , null, "U", ssMng.EmpSeq);
                }
                else
                {
                    bookBank.Insert(lblEmpSeq.Text, null, txtBankAccNo.Text, ddlBank.SelectedValue, ddlBranch.SelectedValue
                        , null, "U", ssMng.EmpSeq);
                }

                GetKeyValue(lblEmpSeq.Text);
                ChangeMode(Main.EditMode.Info);
                //main.ReloadCurrentPage(Page, "บันทึกข้อมูลนี้แล้ว จะทำการรีโหลดหน้าเว็ป");
				//HttpContext.Current.Response.Redirect(Request.Url.OriginalString);
				main.MessageAlert(Page, "บันทึกข้อมูลแล้ว");
            }
            catch (Exception error)
            {
                main.MessageAlert(Page, error.Message);
            }
        }

        protected void Cancel_Click(object sender, EventArgs e)
		{
			GetKeyValue(lblEmpSeq.Text);
            ChangeMode(Main.EditMode.Info);
            //cmdFac.CancelCommand(panelList2, panelGrid, panelCommand);
            //lblMode.Text = "ข้อมูลบุคลากร";
            //DatePickerCommand(false);

            //BindEmployeeType();
            //BindEmployeeStatus();
            //BindPositionType();
            //BindNationalCombo();
            //BindReligionCombo();
            //BindBloodGroupCombo();
            //BindMarStatusCombo();
            //BindPosition();

            //if (Request.QueryString["sta"] != null)
            //{
            //    lblSta.Text = Request.QueryString["sta"];
            //}

            //lblEmpSeq.Text = Session["emp_seq"].ToString();
            //GetKeyValue(lblEmpSeq.Text);
        }

            /*
        protected void btnEditPicture_Click(object sender, EventArgs e)
        {
            RadToolTip2.HideDelay = 100;
            RadToolTip2.AutoCloseDelay = 200;
            RadToolTip2.ShowDelay = 100;
            
            // RadWindow1.
        } */

        protected void cmbPositionType_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            BindClass();
        }

        protected void cmbProvinceHome_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            BindDistrictHome();
        }

        protected void cmbProvinceContact_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            BindDistrictContact();
        }

		protected void cmbPosition_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
		{
			// โหลดประเภทตำแแหน่ง 
			// โหลด Job site
			BindJobSiteAndPositionTypeFromPositionSelected();

			BindClass();
		}

	    #endregion General Event

#region Misc Methods

        private Dictionary<string, string> GetAddress(DataSet ds, int type)
        {
            Dictionary<string, string> resultRow = null;
            if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                return null;

            int? targetAddrSeq = null;
            foreach (DataRow dr in ds.Tables[0].Rows) // Find lastest address of him
            {
                int eachAdrSeq = Convert.ToInt32(dr["ADDRESS_SEQ"]);
                string eachAdrTypeSeq = Convert.ToString(dr["ADDRESS_TYPE_SEQ"]);
                string typeS = type.ToString(CultureInfo.InvariantCulture);
                if ((targetAddrSeq == null && typeS == eachAdrTypeSeq) ||
                    (targetAddrSeq < eachAdrSeq && typeS == eachAdrTypeSeq))
                {
                    targetAddrSeq = eachAdrSeq;
                }
            }

            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                int eachAdrSeq = Convert.ToInt32(dr["ADDRESS_SEQ"]);
                if (eachAdrSeq == targetAddrSeq)
                {
                    resultRow = new Dictionary<string, string>();
                    foreach (DataColumn dc in ds.Tables[0].Columns)
                    {
                        resultRow.Add(dc.ColumnName, Convert.ToString(dr[dc.ColumnName]));
                    }
                    break;
                }
            }
            return resultRow;
        }

        //public void DatePickerCommand(bool bCommand)
        //{
        //    Edit.Visible = !bCommand;
        //    Save_Edit.Visible = bCommand && lblMode.Text == "แก้ไขข้อมูล";
        //    Save_AddNew.Visible = bCommand && lblMode.Text == "เพิ่มข้อมูลใหม่";

        //    txtBirthDate.Visible = bCommand;
        //    txtDateAdmitted.Visible = bCommand;
        //    txtDatePosition.Visible = bCommand;
        //    txtWorkingDate.Visible = bCommand;

        //    lblBirthDate.Text = txtBirthDate.GetStringValue();
        //    lblDateAdmitted.Text = txtDateAdmitted.GetStringValue();
        //    lblDatePosition.Text = txtDatePosition.GetStringValue();
        //    lblWorkingDate.Text = txtWorkingDate.GetStringValue();

        //    lbtEditPicture.Visible = lblMode.Text == "แก้ไขข้อมูล" || lblMode.Text == "เพิ่มข้อมูลใหม่";
        //}

        public DataRow GetEmployee(string Sequence)
        {
            if (Sequence.Length > 0)
            {
                int SequenceI = Convert.ToInt32(Sequence);
                DataSet ds = empBLL.LoadEmployees(SequenceI, "", true, "");

                // Resolve problem, open employee that not active (ex. retired)
                DataTable dt = ds.Tables[0].Rows.Count == 0
                                   ? empBLL.LoadEmployees(SequenceI, "", false, "").Tables[0]
                                   : ds.Tables[0];

                if (dt.Rows.Count > 0)
                    return dt.Rows[0];
            }
            return null;
        }

        private string GetImageUrl(string imageFileName)
        {
            return "~/OtherImages/Person/" + imageFileName;
        }

        private string GetImageFullPath(string imageFileName)
        {
            return Server.MapPath("~/OtherImages/Person/" + imageFileName);
        }

        private void AddItemWithTemplate(ref RadComboBox radComboBox, string itemName, string itemValue, string tableName)
        {

            radComboBox.Items.Add(new RadComboBoxItem(itemName, itemValue));

            TableRow tr = new TableRow();
            TableCell tdClassName = new TableCell();
            Label lblClassName = new Label();
            lblClassName.Text = itemName;
            tdClassName.Width = Unit.Pixel(200);
            tdClassName.Controls.Add(lblClassName);
            tr.Cells.Add(tdClassName);

            (radComboBox.Items[radComboBox.Items.Count - 1].FindControl(tableName)).Controls.Add(tr);
        }

		private void SetLabelText_LabelPositionTypeEditMode(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				lblPositionTypeEditMode.ForeColor = Color.Red;
				lblPositionTypeEditMode.Text = "[ไม่มีข้อมูล]";
				lblPositionTypeEditMode.ToolTip = "ไม่สามารถดึงข้อมูลประเภทตำแหน่งจากตำแหน่งที่เลือกได้ กรุณาติดต่อฝ่ายบุคคล เพื่อให้ตั้งค่าข้อมูลนี้ให้กับตำแหน่งนี้";
			}
			else
			{
				lblPositionTypeEditMode.ForeColor = Color.DodgerBlue;
				lblPositionTypeEditMode.Text = value;
				lblPositionTypeEditMode.ToolTip = null;
			}
		}

		private void SetLabelText_LabelJobSiteEditMode(string value)
		{
			if (string.IsNullOrEmpty(value))
			{
				lblJobSiteEditMode.ForeColor = Color.Red;
				lblJobSiteEditMode.Text = "[ไม่มีข้อมูล]";
				lblJobSiteEditMode.ToolTip = "ไม่สามารถดึงข้อมูลสังกัดหน่วยงานจากตำแหน่งที่เลือกได้ กรุณาติดต่อฝ่ายบุคคล เพื่อให้ตั้งค่าข้อมูลนี้ให้กับตำแหน่งนี้";
			}
			else
			{
				lblJobSiteEditMode.ForeColor = Color.DodgerBlue;
				lblJobSiteEditMode.Text = value;
				lblJobSiteEditMode.ToolTip = null;
			}
		}

        #endregion Misc Method

        protected void LoadBank()
        {
            ddlBank.DataSource = bank.GetBankList();
            ddlBank.DataBind();

            ddlBranch.DataSource = null;
            ddlBranch.DataBind();

            ddlBank.Items.Insert(0, new RadComboBoxItem("--เลือกข้อมูลธนาคาร--", ""));
            ddlBranch.Items.Add(new RadComboBoxItem("--เลือกข้อมูลสาขา--", ""));
        }

        protected void LoadBranch()
        {
            if (!string.IsNullOrEmpty(ddlBank.SelectedValue))
            {
                ddlBranch.DataSource = bank.GetBankBranchList(ddlBank.SelectedValue);
                ddlBranch.DataBind();
            }
            else
            {
                ddlBranch.DataSource = null;
                ddlBranch.DataBind();
            }

            ddlBranch.Items.Insert(0, new RadComboBoxItem("--เลือกข้อมูลสาขา--", ""));
        }

        protected void ddlBank_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            if (!string.IsNullOrEmpty(ddlBank.SelectedValue))
            {
                LoadBranch();
            }
            else
            {
                ddlBranch.DataSource = null;
                ddlBranch.DataBind();
            }
        }

    }
}